const { PersonModel } = require('../db/model')
const login = async (req, res) => {
    const { username, password } = req.body
    const result = await PersonModel.findOne({ username, password })
    if (!result) return res.send({ code: 0, message: '登录失败, 用户名密码错误' })
    if (!result.is_status) return res.send({ code: 0, message: '登录失败,该用户已被禁用' })
    req.session.info = { id: result.id, username: result.username, nickname: result.nickname }
    res.send({ code: 1, message: '登录成功', info: { id: result.id } })
}
const register = async (req, res) => {
    const { username, password, nickname } = req.body
    const result = await PersonModel.findOne({ username })
    if (result) return res.send({ code: 0, message: '注册失败, 用户名重复' })
    await PersonModel({ username, password, nickname }).save()
    res.send({ code: 1, message: '注册成功' })
}
const info = async (req, res) => {
    const id = req.body.id || req.params.id
    const result = await PersonModel.findById(id)
    if (!result) return res.send({ code: 0, message: '没有查到' })
    res.send({
        code: 1,
        message: '查到了',
        info: {
            id: result._id,
            username: result.username,
            age: result.age,
            gender: result.gender,
            nickname: result.nickname,
            avatar: result.avatar
        }
    })
}
const update = async (req, res) => {
    const { id, nickname, age, gender, avatar } = req.body
    console.log(1234);
    console.log(id, nickname, age, gender, avatar);
    await PersonModel.findByIdAndUpdate(id, { nickname, age, gender, avatar })
    res.send({
        code: 1,
        message: '修改成功'
    })
}
const rpwd = async (req, res) => {
    const { id, oldPassword,newPassword } = req.body
    const result = await PersonModel.findById(id)
    
    if(result.password!==oldPassword)return res.send({
        code:0,
        message:'密码错误',
    })
    await PersonModel.findByIdAndUpdate(id,{password:newPassword})
    res.send({
        code:1,
        message:'修改成功'
    })
}
module.exports = {
    login,
    register,
    info,
    update,
    rpwd
}